import express from 'express';
const router = express.Router();

import storage from "../../db/index";


router.get('/', async function (req, res) {
    res.render('mytrades', { data: [], symbol:"" });
});
router.get('/:symbol', async function (req, res, next){
    let symbol= req.params.symbol;
    
    console.log('symbol: ', symbol);
    let myTradeModel = storage.getMyTrade();

    let mytrades = await myTradeModel.findTradeByFilter({symbol:symbol}, {symbol:1,  orderId:1, price:1, qty:1, quoteQty:1, time:1, isBuyer:1, _id:0});
    console.log('mytrades: ', mytrades.length);
    let tradeMap = new Map();
    for(let i=0; i < mytrades.length; i++) {
        let item = mytrades[i];
        if(tradeMap.has(item.orderId)) {
            let sumTrade = tradeMap.get(item.orderId);
            sumTrade.qty += Number(item.qty);
            sumTrade.quoteQty += Number(item.quoteQty);

        }else{
            let sumTrade = {
                orderId:item.orderId,
                price:item.price,
                qty:Number(item.qty),
                quoteQty:Number(item.quoteQty),
                time: item.time,
                isBuyer: item.isBuyer,
            }
            tradeMap.set(item.orderId, sumTrade);
        }
    }
    console.log('tradeMap.size: ', tradeMap.size)
    
    let orders = [];
    
    for(let value of tradeMap.values()){
        console.log('value: ', value);
        orders.push(value);
    };
    orders.sort((a:any,b:any)=> {
        if(a.time >= b.time){
            return -1;
        }else {
            return 1; 
        }
    })


    res.render('mytrades', { data: orders, symbol:symbol });
})

export default router;